
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>

#include "i2c.h"
#include "log.h"

bool I2c::open()
{
	char buf[128];
	sprintf ( buf , "/dev/i2c-%d" , i2c_hw );
	fd = ::open ( buf , O_RDWR );
	if ( fd < 0 ){
		log_printf(LOG_ERROR, "Error opening file:%s\n" , strerror(errno) );
		return false;
	}
	return true;
}

bool I2c::close()
{
	::close(fd);
	return true;
}


bool I2c::write(   uint8_t slave_addr, uint8_t *buf, int len  )
{
	ssize_t res = ::ioctl ( fd , I2C_SLAVE , slave_addr );
	if ( res < 0 ){
		log_printf(LOG_ERROR, "ioctl error: %s\n" , strerror(errno) );
		return false;
	}
	
	res = ::write ( fd , buf , len );
	if ( res < 0 ){
		log_printf(LOG_ERROR, "Error writing file: %s return code=%d\n" , strerror(errno) , res );
		return false;
	}
	if ( len != res ){
		log_printf(LOG_ERROR, "Error write result = %d\n" , res );
		return false;
	}	

	return true;
}


bool I2c::read( uint8_t slave_addr, uint8_t *buf, int len )
{
	ssize_t res = ::ioctl ( fd , I2C_SLAVE , slave_addr );
	if ( res < 0 ){
		log_printf(LOG_ERROR, "ioctl error: %s\n" , strerror(errno) );
		return false;
	}
	
	res = ::read ( fd , buf , len );
	if ( res < 0 ){
		log_printf(LOG_ERROR, "Error reading file: %s return code=%d\n\n" , strerror(errno) , res );
		return false;
	}
	if ( len != res ){
		log_printf(LOG_ERROR, "Error read result = %d\n" , res );
		return false;
	}	
	return true;
}



